<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用 SVG 模拟 Plotly 绘图</title>
    <style>
        svg {
            border: 1px solid #ccc;
        }
        .bar {
            fill: #1f77b4;
        }
        .bar:hover {
            fill: #ff7f0e;
        }
        .label {
            font-family: Arial, sans-serif;
            font-size: 12px;
            text-anchor: middle;
        }
    </style>
</head>
<body>
    <svg id="barChart" width="800" height="400"></svg>
    <script>
        // 柱状图数据
        const data = [4, 8, 15, 16, 23, 42];
        const svg = document.getElementById('barChart');

        // 边距和尺寸
        const margin = { top: 20, right: 20, bottom: 30, left: 40 };
        const width = +svg.getAttribute('width') - margin.left - margin.right;
        const height = +svg.getAttribute('height') - margin.top - margin.bottom;

        // 创建一个 g 元素并应用边距
        const g = svg.append('g')
            .attr('transform', `translate(${margin.left},${margin.top})`);

        // 计算柱子的宽度和间距
        const barWidth = width / data.length - 10;

        // 绘制柱子
        data.forEach((value, index) => {
            const x = index * (barWidth + 10);
            const barHeight = value * 5; // 简单缩放数据以适应画布

            // 创建柱子
            const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            rect.setAttribute('class', 'bar');
            rect.setAttribute('x', x);
            rect.setAttribute('y', height - barHeight);
            rect.setAttribute('width', barWidth);
            rect.setAttribute('height', barHeight);
            g.appendChild(rect);

            // 创建数据标签
            const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
            text.setAttribute('class', 'label');
            text.setAttribute('x', x + barWidth / 2);
            text.setAttribute('y', height - barHeight - 5);
            text.textContent = value;
            g.appendChild(text);
        });
    </script>
</body>
</html>